//
//  FillingDataViewController.m
//  UniversalApp
//
//  Created by 志刚杨 on 2018/2/7.
//  Copyright © 2018年 voidcat. All rights reserved.
//

#import "FillingDataViewController.h"
#import "CYImagePickerViewController.h"
#import "EditUserModel.h"
#import <TZImagePickerController/TZLocationManager.h>
#define HEAD_HEIGHT 100
@interface FillingDataViewController ()<TZImagePickerControllerDelegate>
@property(nonatomic, strong) YYLabel *topTitle;
@property(nonatomic, strong) UIButton *loginHeaderImage;//上传头像按钮
@property(nonatomic, strong) QMUITextField *nickname;
@property(nonatomic, strong) QMUILinkButton *sexMale;//男选择窗
@property(nonatomic, strong) QMUILinkButton *sexFemale;//选择女
@property(nonatomic, strong) UILabel *tips;
@property(nonatomic, strong) QMUIFillButton *submitButton;
@property(nonatomic, strong) UIImage *headerImage;
@property(nonatomic, strong) NSString *sex;

@end

@implementation FillingDataViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //可能有没网的情况重新加载下地理位置
    [[AppDelegate shareAppDelegate] initLocation];
    [self createUI];
}


- (void) createUI{
    //自定义导航栏
    UIButton *navbutton = [[UIButton alloc] initWithFrame:CGRectMake(15, 30, 40, 40)];
    
    [navbutton setImage:IMAGE_NAMED(@"login_back") forState:UIControlStateNormal];
    [navbutton addTarget:self action:@selector(handleBackEvent:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:navbutton];
    
    //标题
    
    _topTitle = [[YYLabel alloc] init];
    NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:ASLocalizedString(@"完善资料(必填)")];
    NSRange range1 = NSMakeRange(0, 4);
    NSRange range2 = NSMakeRange(4, 4);
    
    [text setColor:[UIColor whiteColor] range:range1];
    [text setFont:DEFAULT_BOLDFONT(32) range:range1];
    
    [text setColor:[UIColor qmui_colorWithHexString:@"7F848A"] range:range2];
    [text setFont:DEFAULT_BOLDFONT(20) range:range2];
    
    
    _topTitle.text = ASLocalizedString(@"完善资料(必填)");
    _topTitle.font = DEFAULT_BOLDFONT(32);
    _topTitle.textColor = [UIColor whiteColor];
    _topTitle.textAlignment = NSTextAlignmentCenter;
    _topTitle.attributedText = text;
    [self.view addSubview:_topTitle];
    
    _loginHeaderImage = [[UIButton alloc] init];
    [_loginHeaderImage setImage:IMAGE_NAMED(@"login_ photo") forState:UIControlStateNormal];
    [_loginHeaderImage addTarget:self action:@selector(handleHeaderImageEvent:) forControlEvents:UIControlEventTouchUpInside];
    [_loginHeaderImage setBackgroundColor:[UIColor whiteColor]];
    ViewRadius(_loginHeaderImage, HEAD_HEIGHT/2);
    [self.view addSubview:_loginHeaderImage];
    
    _nickname = [[QMUITextField alloc] init];
    _nickname.backgroundColor = [UIColor clearColor];
    _nickname.qmui_borderColor = [UIColor qmui_colorWithHexString:@"7D7C82"];
    _nickname.qmui_borderPosition = QMUIBorderViewPositionBottom;
    _nickname.qmui_borderWidth = 2;
    _nickname.placeholder = ASLocalizedString(@"昵称");
    _nickname.placeholderColor =  [UIColor qmui_colorWithHexString:@"7D7C82"];
    _nickname.textColor = [UIColor whiteColor];
    [self.view addSubview:_nickname];
    
    _sexMale = [[QMUILinkButton alloc] init];
    [_sexMale setTitle:ASLocalizedString(@"男")forState:UIControlStateNormal];
    _sexMale.underlineColor = [UIColor qmui_colorWithHexString:@"7D7C82"];
    _sexMale.underlineInsets = UIEdgeInsetsMake(4, 0, -4, 0);
    _sexMale.underlineWidth = 1.5;
    _sexMale.titleLabel.font = DEFAULT_BOLDFONT(14);
    [_sexMale setImage:IMAGE_NAMED(@"login_unSelected") forState:UIControlStateNormal];
    [_sexMale setImage:IMAGE_NAMED(@"login_selected") forState:UIControlStateSelected];
    [_sexMale setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _sexMale.imagePosition  = QMUIButtonImagePositionRight;
    _sexMale.imageEdgeInsets = UIEdgeInsetsMake(0, 30, 0, -30);
    [_sexMale addTarget:self action:@selector(handleSexEvent:) forControlEvents:UIControlEventTouchUpInside];
    
    _sexFemale = [[QMUILinkButton alloc] init];
    [_sexFemale setTitle:ASLocalizedString(@"女")forState:UIControlStateNormal];
    _sexFemale.underlineColor = [UIColor qmui_colorWithHexString:@"7D7C82"];
    _sexFemale.underlineInsets = UIEdgeInsetsMake(4, 0, -4, 0);
    _sexFemale.underlineWidth = 2;
    [_sexFemale setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _sexFemale.titleLabel.font = DEFAULT_BOLDFONT(14);
    [_sexFemale setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [_sexFemale setImage:IMAGE_NAMED(@"login_unSelected") forState:UIControlStateNormal];
    [_sexFemale setImage:IMAGE_NAMED(@"login_selected") forState:UIControlStateSelected];
    _sexFemale.imageEdgeInsets = UIEdgeInsetsMake(0, 30, 0, -30);
    [_sexFemale addTarget:self action:@selector(handleSexEvent:) forControlEvents:UIControlEventTouchUpInside];
    _sexFemale.imagePosition  = QMUIButtonImagePositionRight;
    
    [self.view addSubview:_sexMale];
    [self.view addSubview:_sexFemale];
    
    self.tips = [[UILabel alloc] init];
    self.tips.textColor = [UIColor qmui_colorWithHexString:@"E59844"];
    self.tips.text = ASLocalizedString(@"*选择性别后无法更改，请选择真实性别");
    self.tips.font = DEFAULT_FONT(11);
    [self.view addSubview:_tips];
    
    self.submitButton = [[QMUIFillButton alloc] init];
    [self.submitButton setTitle:ASLocalizedString(@"提交")forState:UIControlStateNormal];
    [self.submitButton addTarget:self action:@selector(handleSaveInfoEvent:) forControlEvents:UIControlEventTouchUpInside];
    self.submitButton.fillColor = MainColor;
    [self.view addSubview:_submitButton];
    
    [self.view addSubview:self.tips];
    [self setLayout];
}


-(void)handleBackEvent:(UIButton *)button
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
-(void)handleSexEvent:(QMUILinkButton *)button
{
    _sexFemale.selected = NO;
    _sexMale.selected = NO;
    button.selected = YES;
    
    if(button == _sexMale)
    {
        _sex = @"1";
    }
    else
    {
        _sex = @"2";
    }
}

-(void)handleHeaderImageEvent:(QMUIFillButton *)button
{
    [self selectPhoto];
}

-(void)handleSaveInfoEvent:(QMUIFillButton *)button
{
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:curUser.token forKey:@"token"];
    [param setObject:curUser.id forKey:@"uid"];
    [param setObject:@"ios" forKey:@"type"];
    
    //'sex' : '1男2女',
    
    
    NSString *nickname = self.nickname.text;
    
    if(!StrValid(nickname))
    {
        [MBProgressHUD showTopTipMessage:ASLocalizedString(@"请填写昵称")isWindow:YES];
        return;
    }
    
    if(!StrValid(_sex))
    {
        [MBProgressHUD showTopTipMessage:ASLocalizedString(@"请选择性别")isWindow:YES];
        return;
    }
    
    if(_headerImage == nil)
    {
        [MBProgressHUD showTopTipMessage:ASLocalizedString(@"上传头像")isWindow:YES];
        return;
    }
    
    NSString *address = kAppDelegate.currentCity;
    
    
    [param setObject:nickname forKey:@"user_nickname"];
    [param setObject:_sex forKey:@"sex"];
    [param setObject:address forKey:@"address"];
    
    
    [MBProgressHUD showActivityMessageInView:ASLocalizedString(@"请稍后")];
    
    [PPNetworkHelper uploadImagesWithURL:[cyurl makeURLWithC:@"login_api" A:@"perfect_reg_info"] parameters:param name:@"avatar" images:@[_headerImage] fileNames:@[@"avatar.png"] imageScale:1 imageType:@"png" progress:^(NSProgress *progress) {
        
    } success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        if([[responseObject valueForKey:@"code"] intValue] == 1)
        {
            //首次储存一下性别
            curUser.sex = [_sex integerValue];
            //            curUser.level = model.level;
            [userManager saveUserInfo];
            
            [MBProgressHUD showTopTipMessage:ASLocalizedString(@"资料已更新")];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[EditUserModel new] updateUserinfo:^(BOOL success) {
                    KPostNotification(KNotificationLoginStateChange, @YES)
                }];
            });
            
        }
        else
        {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showTopTipMessage:[responseObject valueForKey:@"msg"] isWindow:YES];
            
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[EditUserModel new] updateUserinfo:^(BOOL success) {
                    KPostNotification(KNotificationLoginStateChange, @YES)
                }];
            });
            
        }
        
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUD];
    }];
    
}



-(void)setLayout
{
    [_topTitle mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(@60);
        make.centerX.equalTo(self.view);
    }];
    
    //头头像
    [_loginHeaderImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(_topTitle.mas_bottom).offset(50);
        make.width.equalTo(@HEAD_HEIGHT);
        make.height.equalTo(@HEAD_HEIGHT);
    }];
    
    //昵称输入
    [_nickname mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@60);
        make.width.equalTo(self.view).offset(-100);
        make.centerY.equalTo(self.view);
        make.centerX.equalTo(self.view);
    }];
    
    //性别选项卡
    [_sexMale mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nickname.mas_bottom).offset(5);
        make.left.equalTo(_nickname);
        make.width.equalTo(_nickname).multipliedBy(0.5);
        make.height.equalTo(@40);
    }];
    
    [_sexFemale mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_nickname.mas_bottom).offset(5);
        make.left.equalTo(_sexMale.mas_right);
        make.width.equalTo(_nickname).multipliedBy(0.5);
        make.height.equalTo(@40);
    }];
    
    //提示
    [_tips mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(_nickname);
        make.top.equalTo(_sexMale.mas_bottom).offset(2);
    }];
    
    [_submitButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_tips.mas_bottom).offset(20);
        make.centerX.equalTo(self.view);
        make.height.equalTo(@40);
        make.width.equalTo(_nickname);
    }];
    
}


-(void)selectPhoto
{
    CYImagePickerViewController *imagePickerVc = [[CYImagePickerViewController alloc] initWithMaxImagesCount:1 delegate:self];
    [imagePickerVc.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    imagePickerVc.naviBgColor = [UIColor blackColor];
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    
    
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initCropTypeWithAsset:assets[0] photo:photos[0] completion:^(UIImage *cropImage, id asset) {
            _headerImage = cropImage;
            [_loginHeaderImage setImage:_headerImage forState:UIControlStateNormal];
        }];
        imagePicker.needCircleCrop = NO;
        imagePicker.circleCropRadius = 110;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    imagePickerVc.naviTitleColor = [UIColor blackColor];
    imagePickerVc.barItemTextColor =  [UIColor blackColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor blackColor];
    imagePickerVc.showSelectBtn = YES;
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

@end

